using B.S.Data.MES.API.Applications.BaseData.Command.CustomerCommand;
using B.S.Domain.基础数据.客户管理;
using B.S.Infratrctrue;
using B.S.Requst;
using CSRedis;
using MediatR;

namespace B.S.Data.MES.API.Applications.BaseData.CommandHandlers.CustomerCommandHandlers
{
    public class ListCustomerCommandHandlers : IRequestHandler<ListCustomerCommand, APIRequst<APIPageing<List<client>>>>
    {
        private readonly IBaseRepository<client> customerRepository;

        public ListCustomerCommandHandlers(IBaseRepository<client> customerRepository)
        {
            this.customerRepository = customerRepository;
        }

        public async Task<APIRequst<APIPageing<List<client>>>> Handle(ListCustomerCommand request, CancellationToken cancellationToken)
        {
            APIRequst<APIPageing<List<client>>> response = new APIRequst<APIPageing<List<client>>>();
            response.Code = RequstCode.成功;
            response.Msg = RequstCode.成功.ToString();
            var query = customerRepository.GetAll().Where(x => x.isDel == false);
            // 分页
            var totalCount = query.Count();
            var total = (int)Math.Ceiling(1.0 * totalCount / request.PageSize);
            var customers = query.OrderBy(x => x.CustomerID).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            // 构造返回结果
            var pageResult = new APIPageing<List<client>>
            {
                Data = customers,
                Total= total,
                TotalCount= totalCount,
            };

            response.Data = pageResult;
            return await Task.FromResult(response);
        }
    }
}